package com.easondongh.system.aspect;

import com.alibaba.fastjson.JSON;
import com.easondongh.system.common.ActiveUser;
import com.easondongh.system.constants.Constants;
import com.easondongh.system.domain.SysLog;
import com.easondongh.system.domain.SysUser;
import com.easondongh.system.service.SysLogService;
import com.easondongh.system.utils.StringUtils;
import com.easondongh.system.utils.ThreadLocalContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * @author EasonDongH
 * @date 2020/4/30 13:15
 */
@Aspect
@Slf4j
@Component
public class LogAspect {

    @Autowired
    private SysLogService logService;

    @Pointcut("execution( * com.easondongh.*.controller..*(..))")
    public void logPointCut() { }

    /**
     * 方法执行之前调用
     */
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Exception {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        // 记录下请求内容
        printRequestLog(joinPoint, request, uri);
    }

    /**
     * 环绕通知
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object ob = pjp.proceed();
        long time = System.currentTimeMillis() - startTime;
        log.info("耗时 : {}", time);
        SysLog logger = ThreadLocalContext.get().getLogger();
        logger.setResponseTime(time);
        return ob;
    }

    /**
     * 后置通知
     * @param ret
     */
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) {
        String result = JSON.toJSONString(ret);
        log.info("返回值：{}", JSON.toJSONString(ret));
        SysLog logger = ThreadLocalContext.get().getLogger();
        if(result != null && result.length() > 1000) {
            result = result.substring(0,1000);
        }
        logger.setResponseResult(result);
        logger.setCreateTime(new Date());
        logService.save(logger);
    }

    /**
     * 异常通知
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "logPointCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        SysLog logger = ThreadLocalContext.get().getLogger();
        logger.setResponseStatus(Constants.REQUEST_ERROR);
        String exception = StringUtils.getPackageException(e, "com.jg");
        logger.setResponseError(exception);
        logger.setResponseTime(0L);
        logger.setCreateTime(new Date());
        logService.save(logger);
    }

    /**
     * 打印请求日志
     * @param joinPoint
     * @param request
     * @param uri
     */
    private void printRequestLog(JoinPoint joinPoint, HttpServletRequest request, String uri) {
        // 拿到切面方法
        log.info("请求地址 : {}", uri);
        log.info("请求方式 : {}", request.getMethod());
        // 获取真实的ip地址
        String ip = StringUtils.getRemoteIp(request);
        log.info("IP : {}", ip);
        String controllerName = joinPoint.getSignature().getDeclaringTypeName();
        log.info("方法 : {}.{}", controllerName, joinPoint.getSignature().getName());
        String params = Arrays.toString(joinPoint.getArgs());
        log.info("请求参数：{}", params);
        // 获取日志实体
        SysLog logger = ThreadLocalContext.get().getLogger();
        logger.setRequestUrl(uri);
        if(params != null && params.length() > 1000) {
            params = params.substring(0,1000);
        }
        logger.setRequestParams(params);
        logger.setResponseStatus(Constants.REQUEST_SUCCESS);
        logger.setRequestMethod(request.getMethod());
        logger.setLoginIp(ip);
        try {
            Subject subject = SecurityUtils.getSubject();
            ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
            if(null != activeUser){
                SysUser user = activeUser.getUser();
                logger.setLoginId(user.getId());
                logger.setLoginName(user.getLoginName());
            }
        } catch (Exception ex) {
            log.error("日志AOP获取登录用户信息异常", ex);
        }
    }
}
